<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ include file="../session.jsp"%>
<!DOCTYPE html>
<html lang="ko">
  <head>
  	<%@ include file="../head.jsp"%>
  	<style>
  		#modalId {
  			width: 800px;
  		}
		.alert
		{
		    display: none;
		}
  	</style>
  	<link href="assets/css/prettify.css" rel="stylesheet" />
  </head>
  <body>
  	<%@ include file="../menu.jsp"%>
  	
  	<!-- .modal -->
	<div id="myModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
		<!-- .modal-dialog -->
		<div class="modal-dialog" id="modalId">
			<!-- .modal-content -->
			<div class="modal-content">
				<!-- 제목 -->
				<div class="modal-header">
					<!-- 닫기버튼 -->
					<button type="button" class="close" data-dismiss="modal" aria-hidden="true">
						&times;
					</button>
					<h4 class="modal-title" id="myModalLabel">카테고리 추가하기</h4>
				</div>
				<!-- 내용 -->
				<div class="row">
					<div class="col-md-2"></div>
					<div class="col-md-4">
						<select class="form-control" name="firstCategory">
							<option value="default">- 1차카테고리 -</option>
							<c:forEach items="${first}" var="first">
								<option value="${first.idFirstCategory}">${first.firstCategoryText}</option>
							</c:forEach>
						</select>
					</div>
					<div class="col-md-4">
						<select class="form-control" name="secondCategory">
							<option value="default">- 1차를 먼저 선택하여 주세요 -</option>
						</select>
					</div>
					<div class="col-md-2"></div>
				</div>
				<!-- 하단 -->
				<div class="modal-footer">
					<button type="button" class="btn btn-default" data-dismiss="modal">
						닫기
					</button>
					<button type="button" class="btn btn-primary" id="cateAdd">
						추가
					</button>
				</div>
			</div>
			<!-- /.modal-content -->
		</div>
		<!-- /.modal-dialog -->
	</div>
	<!-- /.modal -->
  	
	<div class="container">
		<div class="page-header">
			<h2>신규 제품 추가 - <small>새로운 제품을 추가하세요.</small></h2>
		</div>

		<form id="insertProduct" class="form-horizontal" role="form" method="post" action="listProduct.do" enctype="multipart/form-data">
			<fieldset>
				<div class="form-group">
					<label for="brand" class="col-md-2 control-label">브랜드</label>
					<div class="col-md-10">
						<select name="brand" class="form-control">
							<option>- 선택하세요 -</option>
							<c:forEach items="${brand}" var="brand">
								<option value="${brand.idBrand}" <c:if test="${brand.idBrand == idBrand}">selected</c:if>>${brand.brandTitle}</option>
							</c:forEach>
						</select>
					</div>
				</div>
				
				<div class="form-group">
					<label for="productTitle" class="col-md-2 control-label">제품명</label>
					<div class="col-md-10">
						<input type="text" class="form-control" autocomplete="off" name="productTitle" placeholder="제품명을 입력하세요" autofocus/>
					</div>
				</div>
				
				<div class="form-group">
					<label for="first" class="col-md-2 control-label">카테고리</label>
					<div class="col-md-10">
						<p class="form-control-static">
							<a data-toggle="modal" href="#myModal" id="cateAddClick">추가하기</a>
						</p>
						<div id="category_add"></div>
					</div>
				</div>

				<div class="form-group">
					<label for="productImg" class="col-md-2 control-label">사진</label>
					<div class="col-md-10">
						<input type="file" class="form-control" name="imgFile"/>
					</div>
				</div>

				<div class="form-group">
					<label for="volume" class="col-md-2 control-label">용량</label>
					<div class="col-md-10">
						<input type="text" class="form-control" name="volume" placeholder="용량을 입력하세요"/>
					</div>
				</div>

				<div class="form-group">
					<label for="price" class="col-md-2 control-label">가격</label>
					<div class="col-md-10">
						<input type="number" class="form-control" name="price" placeholder="가격을 입력하세요"/>
					</div>
				</div>

				<div class="form-group">
					<label for="colorType" class="col-md-2 control-label">컬러/타입</label>
					<div class="col-md-10">
						<textarea name="colorType" class="form-control" rows="7" placeholder="컬러/타입을 입력하세요"></textarea>
					</div>
				</div>
				
				<div class="form-group">
					<label for="productText" class="col-md-2 control-label">제품설명</label>
					<div class="col-md-10">
						<textarea name="productText" class="form-control" rows="10" placeholder="제품설명을 입력하세요"></textarea>
					</div>
				</div>

				<div class="form-group">
					<div class="col-md-offset-2 col-md-10">
						<div class="row">
							<div class="col-md-6">
								<button type="submit" class="btn btn-primary btn-block">저장하기</button>
							</div>
							<div class="col-md-6">
								<button type="reset" class="btn btn-warning btn-block">다시작성</button>
							</div>
						</div>
					</div>
				</div>

			</fieldset>
		</form>
	</div>
	<!-- Javascript -->
	<script src="assets/js/jquery.js"></script>
	<script src="assets/js/bootstrap.min.js"></script>
    <script src="assets/js/typehead/jquery.mockjax.js"></script>
    <script src="assets/js/typehead/bootstrap-typeahead.js"></script>
    
    <script>
    	$(function() {
    		
    		$.mockjax({
                url: '/cities/list',
                response: function() {
                	var typehead = $("input[name='productTitle']").val();
                	var asdf = [{ name: '아나다'}, { name: 'Mark'}, { name: 'Jacob'}];
                	$.ajax({
    					url: "ajax/json.jsp",
    					data: "typehead=" + typehead,
    					dataType: "text",
    					timeout: 30000,
    					cache: false,
    					async: false,
    					success: function(req) {
    						asdf = eval(req);
    					},
    					error: function(xhr, status, error) {
    						alert("status: " + status + " / error-code: " + xhr.status + " " + error);
    					}
    				});
                    this.responseText = asdf;
                }
            });

    		$("input[name='productTitle']").typeahead({
                ajax: '/cities/list'
            });
    		
    		/* $("input[name='productTitle']").keyup(function() {
    			
    			var typehead = $("input[name='productTitle']").val();
    			
    			$.ajax({
					url: "ajax/json.jsp",
					data: "typehead=" + typehead,
					dataType: "text",
					timeout: 30000,
					cache: false,
					async: false,
					success: function(req) {
						var asdf = [{ name: '아나다'}, { name: 'Mark'}, { name: 'Jacob'}];
		    			
						asdf = eval(req);
		    			
		   		        $("input[name='productTitle']").typeahead({
		   		        	source: asdf
		   		        });
					},
					error: function(xhr, status, error) {
						alert("status: " + status + " / error-code: " + xhr.status + " " + error);
					}
				});
    		}); */
    	});
    </script>
    
	
	<!-- 형식검사 클래스 참조 -->
	<script src="assets/js/string.js"></script>
	<script type="text/javascript">
		$(function() {
			
			arr = new Array();
			
			$("select[name='firstCategory']").change(function() {
				$("select[name='secondCategory']").empty();
				
				var first = $(this).find("option:selected").val();
				
				$("select[name='thirdCategory'] option").remove();
				$("select[name='thirdCategory']").append("<option value='default'>- 2차를 먼저 선택하여 주세요 -</option>");
				
				$.ajax({
					url: "ajax/first.jsp",
					data: "first=" + first,
					dataType: "xml",
					timeout: 30000,
					cache: false,
					async: false,
					success: function(req) {
						$(req).find("item").each(function() {
							var idSecondCategory = $(this).find("idSecondCategory").text();
							var secondCategoryText = $(this).find("secondCategoryText").text();
							
							var option = $("<option>").html(secondCategoryText);
							option.attr({'value' : idSecondCategory});
							
							$("select[name='secondCategory']").append(option);
						});
					},
					error: function(xhr, status, error) {
						alert("status: " + status + " / error-code: " + xhr.status + " " + error);
					}
				});
			});
			
			$("#cateAdd").click(function() {
				
				var firstVal = $("select[name='firstCategory']").val();
				var firstText = $("select[name='firstCategory'] option:selected").text();
				var secondVal = $("select[name='secondCategory']").val();
				var secondText = $("select[name='secondCategory'] option:selected").text();
				if (firstVal == 'default') {
					alert('1차카테고리를 선택하세요.');
					return false;
				}
				if (secondVal == 'default') {
					alert('2차카테고리를 선택하세요.');
					return false;
				}
				
				for (var i=0; i<arr.length; i++) {
					if (arr[i] == secondVal) {
						alert("동일한 2차카테고리는 선택하실수 없습니다.");
						return false;
					}
				}
				
				var result = "<div class='row cate_item'><div class='col-md-5'><select class='form-control' name='first'>"
					+ "<option value='" + firstVal + "'>" + firstText + "</option></select></div><div class='col-md-5'>"
					+ "<select class='form-control' name='second'><option value='" + secondVal + "'>" + secondText + "</option>"
					+ "</select></div><div class='col-md-2'><input type='button' class='btn btn-block' id='del"
					+ secondVal + "' value='삭제'/></div><script>$(function(){$('#del" + secondVal + "').click(function(){if(confirm"
					+ "('정말 삭제하시겠습니까?')){$(this).parents('.cate_item').remove();arr=jQuery.grep(arr,function(value)"
					+ "{return value != " + secondVal + ";});}});});</sc" + "ript><div><label for='keyWord' class='col-md-1 control-label'>키워드</label><div class='col-md-11' id='keyWord" + secondVal + "'></div></div><div>&nbsp;</div></div>";
					
				$("#category_add").append(result);
				
				$.ajax({
					url: "ajax/keyword.jsp",
					data: "second=" + secondVal,
					dataType: "xml",
					timeout: 30000,
					cache: false,
					async: false,
					success: function(req) {
						$(req).find("item").each(function() {
							var name = $(this).find("name").text();
							var item = "<label class='checkbox-inline'><input type='checkbox' name='keyWord' value='" + name + "'>" + name + "</label>";
							$("#keyWord" + secondVal).append(item);
						});
					},
					error: function(xhr, status, error) {
						alert("status: " + status + " / error-code: " + xhr.status + " " + error);
					}
				});
				
				arr.push(secondVal);
				
				$('#myModal').modal('hide');
			});
			
			$("#cateAddClick").click(function() {
				$("select[name='firstCategory'] option:eq(0)").attr("selected", "selected");
				$("select[name='secondCategory'] option").remove();
				$("select[name='secondCategory']").append("<option value='default'>- 1차를 먼저 선택하여 주세요 -</option>");
			});
			
		});
	</script>
	
	<script type="text/javascript">
		$(function() {
			$("#insertProduct").submit(function() {
				
				if ($("select[name='brand'] > option:selected").index() < 1) {
					alert("브랜드를 선택하세요.");
					$("select[name='brand']").focus();
					return false;
				}
				
				if (!$("input[name='productTitle']").val().isValue()) {
					alert("제품명을 입력하세요.");
					$("input[name='productTitle']").focus();
					return false;
				}
				
				if ($("select[name='first'] > option:selected").index() != 0) {
					alert("카테고리를 선택하세요.");
					return false;
				}
				
				if ($("select[name='second'] > option:selected").index() != 0) {
					alert("2차 카테고리를 선택하세요.");
					return false;
				}
				
				var image = true;
				$("input[name='imgFile']").each(function(idx, item) {
					if (!$(item).val().isValue()) {
						alert("사진을 추가하세요.");
						$(item).focus();
						image = false;
					}
				});
				if (!image) {
					return false;
				}
				
				if (!$("input[name='volume']").val().isValue()) {
					alert("용량을 입력하세요.");
					$("input[name='volume']").focus();
					return false;
				}
				
				if (!$("input[name='price']").val().isValue()) {
					alert("가격을 입력하세요.");
					$("input[name='price']").focus();
					return false;
				}
				
				if (!$("input[name='price']").val().isNumber()) {
					alert("가격은 숫자로만 입력이 가능합니다.");
					$("input[name='price']").focus();
					return false;
				}
				
				if (!$("input[name='keyWord']").val().isValue()) {
					alert("키워드를 입력하세요.");
					$("input[name='keyWord']").focus();
					return false;
				}
				
				if (!$("textarea[name='productText']").val().isValue()) {
					alert("제품설명을 입력하세요.");
					$("textarea[name='productText']").focus();
					return false;
				}
				
				if (!confirm("정말 등록하시겠습니까?")) {
					return false;
				}
				
			});
		});
	</script>
  </body>
</html>